<template>
    <div class="create-post-page w-75 mx-auto">
        <h4>{{ isEditMode? '编辑文章': '新建文章' }}</h4>
        <Uploader action="/upload"
            class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
            :beforeUpload="uploadCheck" @file-uploaded="handleFileUploaded" :uploaded="uploadedData">
            <h2>点击上传头图</h2>
            <template #loading>
                <div class="d-flex">
                    <div class="spinner-border text-secondary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <h2>正在上传...</h2>
                </div>
            </template>
            <template #uploaded="dataProps">
                <div class="uploaded-area">
                    <img :src="dataProps.uploadedData.data.url">
                    <h3>点击重新上传</h3>
                </div>
            </template>
        </Uploader>
        <ValidateForm @form-submit="onFormSubmit">
            <div class="mb-3">
                <label class="form-label">文章标题：</label>
                <ValidateInput placeholder="请输入文章标题" :rules="titleRules" v-model="titleVal"></ValidateInput>
            </div>
            <div>
                <label class="form-label">文章详情：</label>
                <ValidateInput placeholder="请输入文章详情" :rules="contentRules" v-model="contentVal" tag="textarea"
                    rows="10">
                </ValidateInput>
            </div>
            <template #submit>
                <button class="btn btn-primary btn-large">{{ isEditMode? '保存': '新建文章' }}</button>
            </template>
        </ValidateForm>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { GlobalDataProps, PostProps, ResponseType, ImageProps } from '../store'
import ValidateForm from '@/components/ValidateForm.vue'
import ValidateInput, { RulesProp } from '@/components/ValidateInput.vue'
import Uploader from '@/components/Uploader.vue'
import axios from 'axios'
import { beforeUploadCheck } from '../helper'
import CreateMessage from '@/components/CreateMessage'
export default defineComponent({
    name: 'CreatePost',
    components: {
        ValidateForm,
        ValidateInput,
        Uploader
    },
    setup() {
        let imageId = ''
        const uploadedData = ref()
        const titleVal = ref('')
        const titleRules: RulesProp = [{
            type: 'required',
            message: '文章标题不能为空'
        }]
        const contentVal = ref('')
        const contentRules: RulesProp = [
            {
                type: 'required',
                message: '文章详情不能为空'
            }
        ]
        const store = useStore<GlobalDataProps>()
        const router = useRouter()
        const route = useRoute()
        // 加两个感叹号把这个表达式变成布尔值
        const isEditMode = !!route.query.id
        onMounted(() => {
            if (isEditMode) {
                store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
                    const currentPost = rawData.data
                    if (currentPost.image) {
                        uploadedData.value = { data: currentPost.image }
                    }
                    titleVal.value = currentPost.title
                    contentVal.value = currentPost.content || ''
                })
            }
        })
        const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
            if (rawData.data._id) {
                imageId = rawData.data._id
            }
        }
        const onFormSubmit = (result: boolean) => {
            if (result) {
                const { column, _id } = store.state.user
                if (column) {
                    const newPost: PostProps = {
                        title: titleVal.value,
                        content: contentVal.value,
                        column,
                        author: _id
                    }
                    if (imageId) {
                        newPost.image = imageId
                    }
                    const actionName = isEditMode ? 'updatePost' : 'createPost'
                    const sendData = isEditMode
                        ? {
                            id: route.query.id,
                            payload: newPost
                        }
                        : newPost
                    store.dispatch(actionName, sendData).then(() => {
                        CreateMessage('发表成功，2s秒后跳转至文章', 'success', 2000)
                        setTimeout(() => {
                            router.push({ name: 'column', params: { id: column } })
                        }, 2000)
                    })
                }
            }
        }
        const handleFileChange = (e: Event) => {
            // 在这个input组件中拿到选择的file对象
            const target = e.target as HTMLInputElement
            const files = target.files
            // files是一个列表，但不是数组，是一个类数组的对象
            if (files) {
                const uploadFile = files[0]
                const formData = new FormData()
                formData.append(uploadFile.name, uploadFile)
                axios.post('/upload', formData, {
                    Headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(resp => {
                    console.log(resp)
                })
            }
        }
        const uploadCheck = (file: File) => {
            const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 2 })
            const { passed, error } = result
            if (error === 'format') {
                CreateMessage('上传图片只能是JPG/PNG格式', 'error')
            }
            if (error === 'size') {
                CreateMessage('图片大小不能超过2MB', 'error')
            }
            return passed
        }
        return {
            titleVal,
            titleRules,
            contentVal,
            contentRules,
            onFormSubmit,
            handleFileChange,
            uploadCheck,
            handleFileUploaded,
            uploadedData,
            isEditMode
        }
    }
})
</script>
<style>
.create-post-page .file-upload-container {
    height: 200px;
    cursor: pointer;
    overflow: hidden;
}

.create-post-page .file-upload-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.uploaded-area {
    position: relative;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.uploaded-area:hover h3 {
    display: block;
}

.uploaded-area h3 {
    display: none;
    position: absolute;
    color: #999;
    text-align: center;
    width: 100%;
    top: 50%;
}
</style>
